package com.isoftstone.framework.controller;


import com.isoftstone.framework.domain.Tidings;
import com.isoftstone.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 修改时间：2015、12、11
 */
@ControllerAdvice
@Slf4j
public class ErrorController {

	private boolean isAjaxRequest(HttpServletRequest request){
		return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
	}

	@ExceptionHandler(value = {Exception.class})
	public ModelAndView exception(HttpServletRequest req, HttpServletResponse res, Exception e) {

		log.error("**************************ERROR START************************");
		log.error("程序异常",e);
		log.error("**************************ERROR START************************");

		if(isAjaxRequest(req)){
			Tidings error;
			if(e.getMessage() != null){
				error = Tidings.error(e.getMessage().replaceAll("'","").replaceAll("\"",""));

			}else{
				error = Tidings.error("程序异常!");
			}

			//res.setContentType("text/html;charset=UTF-8");
			res.setContentType("application/json;charset=UTF-8");

			try {
				res.getWriter().write(JsonUtil.beanToJson(error));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}else{
			if(e instanceof UnauthorizedException || e instanceof UnauthenticatedException){
				return new ModelAndView("/error/noauth","exception",e.getMessage());
			}
			return new ModelAndView("/error/error","exception",e.getMessage());
		}

		return null;
	}

}
